<template>
  <div class="group flex">
    <div class="flex flex_d-column">
      <div class="padding-n-10 flex flex_j_c-space-between">
        <el-button type="primary" @click="createGroupDialog = true">创建群聊</el-button>
        <el-button type="primary" @click="searchDialogVisible = true">
          <el-icon><EpSearch /></el-icon>搜索群聊
        </el-button>
      </div>
      <el-scrollbar class="width-280 padding-n-10">
        <el-collapse v-model="activeCollapse">
          <el-collapse-item title="我的群组" name="1">
            <TransitionGroup tag="div" name="move">
              <Card
                v-for="group in groupList"
                :key="group.id"
                class="card"
                :image="group.avatar || defaultAvatar"
                :label="group.name"
                :content="`${group.memberCount || 0}人`"
                :active="selectedGroup?.id === group.id"
                @click="selectGroup(group)">
              </Card>
            </TransitionGroup>
          </el-collapse-item>
        </el-collapse>
      </el-scrollbar>
    </div>

    <!-- 群组详情面板 -->
    <div class="group-panel padding-15 flex_d-column flex_a_i-center flex-item_f-1">
      <template v-if="selectedGroup">
        <GroupPanel class="group-panel-info margin_t-50" :group="selectedGroup"></GroupPanel>
        <div class="margin_t-10">
          <el-button type="primary" plain round @click="enterGroup(selectedGroup)">
            <el-icon class="margin_r-5"><EpPromotion /></el-icon>
            发送消息
          </el-button>
          <template v-if="isGroupOwner">
            <el-button
              type="danger" 
              plain 
              round 
              @click="disbandGroup">
              <el-icon class="margin_r-5"><EpDelete /></el-icon>
              解散群组
            </el-button>
          </template>
          <template v-else>
            <el-button 
              type="warning" 
              plain 
              round 
              @click="quitGroup">
              <el-icon class="margin_r-5"><EpDelete /></el-icon>
              退出群组
            </el-button>
          </template>
        </div>

        <div class="group-info margin_t-20 width-100">
          <div class="info-item">
            <label>群公告：</label>
            <p>{{ selectedGroup.announcement || '暂无公告' }}</p>
          </div>
          <div class="info-item">
            <label>群描述：</label>
            <p>{{ selectedGroup.description || '暂无描述' }}</p>
          </div>
          <div class="info-item">
            <label>群成员：</label>
            <p>{{ selectedGroup.memberCount || 0 }}人</p>
          </div>
          <div class="info-item">
            <label>创建时间：</label>
            <p>{{ selectedGroup.createTime || '-' }}</p>
          </div>
        </div>
      </template>
      <Empty v-else></Empty>
    </div>

    <!-- 创建群聊对话框 -->
    <el-dialog v-model="createGroupDialog" title="创建群聊" width="30%">
      <el-form :model="groupForm" label-width="80px">
        <el-form-item label="群名称" required>
          <el-input v-model="groupForm.name" placeholder="请输入群名称"></el-input>
        </el-form-item>
        <el-form-item label="群描述">
          <el-input v-model="groupForm.description" type="textarea" placeholder="请输入群描述"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createGroupDialog = false">取消</el-button>
        <el-button type="primary" @click="createGroup">创建</el-button>
      </template>
    </el-dialog>
    
    <!-- 搜索群聊对话框 -->
    <SearchGroupDialog 
      v-model="searchDialogVisible"
      @join="handleJoinGroup"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useConversationStore, useRoomStore, useUserStore } from '@/stores'
import { 
  createRoomApi, 
  listRoomsApi, 
  getRoomDetailApi, 
  exitRoomApi, 
  disbandRoomApi
} from '@/api/room'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Promotion as EpPromotion, Delete as EpDelete, Search as EpSearch } from '@element-plus/icons-vue'
import Card from '@/components/card/index.vue'
import GroupPanel from '@/components/group-panel/index.vue'
import Empty from '@/components/empty/index.vue'
import SearchGroupDialog from './components/search-group-dialog/index.vue'

// 定义组件名称，使keep-alive能够正确缓存
defineOptions({
  name: 'Group'
})

const router = useRouter()
const conversationStore = useConversationStore()
const roomStore = useRoomStore() // 使用room store
const userStore = useUserStore() // 使用user store
const createGroupDialog = ref(false)
const searchDialogVisible = ref(false) // 搜索对话框可见性
const selectedGroup = ref(null)
const activeCollapse = ref(['1'])
const defaultAvatar = '/src/assets/images/group.png'

// 使用store中的群组数据
const groupList = computed(() => roomStore.groupRooms)

const groupForm = ref({
  name: '',
  description: ''
})

const isGroupOwner = computed(() => {
  if (!selectedGroup.value) return false
  const currentUserId = Number(userStore.id)  // 使用数字主键
  const ownerIdNum = Number(selectedGroup.value.ownerId)
  console.log('当前用户ID:', currentUserId, '群主ID:', ownerIdNum) // 添加日志便于调试
  return ownerIdNum === currentUserId
})

// 获取群聊列表
const fetchGroupList = async () => {
  try {
    const response = await listRoomsApi()
    if (response && response.code === 200 && response.data) {
      // 使用store保存群组数据
      roomStore.groupRooms = response.data
    }
  } catch (error) {
    ElMessage.error('获取群聊列表失败')
    console.error('获取群聊列表失败:', error)
  }
}

// 选择群组
const selectGroup = async (group) => {
  try {
    // 先设置选中状态，避免界面闪烁
    selectedGroup.value = group
    
    // 获取群组详情
    const response = await getRoomDetailApi(group.id)
    if (response && response.code === 200 && response.data) {
      // 更新群组详情
      const updatedGroup = {
        ...response.data,
        // 确保所有必要的字段都存在，并进行类型转换
        id: Number(response.data.id),
        ownerId: Number(response.data.ownerId),
        description: response.data.description || '',
        memberCount: Number(response.data.memberCount) || 0,
        onlineCount: Number(response.data.onlineCount) || 0,
        createTime: response.data.createTime || '',
      }
      console.log('更新后的群组数据:', updatedGroup) // 添加日志便于调试
      selectedGroup.value = updatedGroup
      
      // 更新群组列表中的数据
      const index = roomStore.groupRooms.findIndex(g => g.id === updatedGroup.id)
      if (index !== -1) {
        roomStore.groupRooms[index] = updatedGroup
      }
    } else {
      ElMessage.error('获取群组详情失败')
    }
  } catch (error) {
    console.error('获取群组详情失败:', error)
    ElMessage.error('获取群组详情失败')
  }
}

// 创建群聊
const createGroup = async () => {
  if (!groupForm.value.name) {
    ElMessage.warning('群名称不能为空')
    return
  }
  
  try {
    const response = await createRoomApi({
      name: groupForm.value.name,
      description: groupForm.value.description,
      avatar: defaultAvatar // 使用默认头像
    })
    
    if (response && response.code === 200) {
      ElMessage.success('创建群聊成功')
      
      // 将新创建的群组添加到 store
      if (response.data) {
        const newGroup = {
          ...response.data,
          avatar: response.data.avatar || defaultAvatar
        }
        roomStore.groupRooms.unshift(newGroup) // 添加到列表开头
        
        // 自动选中新创建的群组
        selectGroup(newGroup)
      }
      
      // 关闭对话框并重置表单
      createGroupDialog.value = false
      groupForm.value = {
        name: '',
        description: ''
      }
    } else {
      ElMessage.error(response?.message || '创建群聊失败')
    }
  } catch (error) {
    console.error('创建群聊失败:', error)
    ElMessage.error(error?.response?.data?.message || '创建群聊失败，请稍后重试')
  }
}

// 进入群聊
const enterGroup = (group) => {
  // 构造完整的群聊会话对象
  const conversation = {
    id: group.conversationId || group.id,
    roomId: group.roomId || group.id,
    userId: userStore.id,  // 使用数字主键
    message: null,
    friend: null,
    group: {
      id: group.id,
      name: group.name,
      avatar: group.avatar || defaultAvatar,
      ownerId: group.ownerId,
      memberCount: group.memberCount,
      onlineCount: group.onlineCount
    }
  }
  
  // 直接设置完整的会话对象
  conversationStore.active = conversation
  
  router.push({ name: 'conversation' })
}

// 解散群组
const disbandGroup = async () => {
  if (!selectedGroup.value) return
  
  try {
    await ElMessageBox.confirm(
      '解散群组后，所有成员将被移除，且所有消息将被删除，确定要解散吗？',
      '解散群组',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const groupId = selectedGroup.value.id
    
    // 在发送解散请求前，先从列表中移除该群聊
    roomStore.groupRooms = roomStore.groupRooms.filter(g => g.id !== groupId)
    selectedGroup.value = null
    
    // 检查并从会话列表中移除
    const updatedConversations = conversationStore.list.filter(conversation => {
      return !(conversation.group && conversation.group.id === groupId)
    })
    conversationStore.list = updatedConversations
    
    // 如果当前正在查看该群聊，则清除活跃会话
    if (conversationStore.active && conversationStore.active.group && conversationStore.active.group.id === groupId) {
      conversationStore.setActive(null)
    }
    // 发送解散请求
    const response = await disbandRoomApi(groupId)
    if (response && response.code === 200) {
      ElMessage.success('群组已解散')
    } else {
      ElMessage.error(response?.message || '解散群组失败')
      // 如果解散失败，重新获取群聊列表
      await roomStore.getGroupRooms()
    }
  } catch (error) {
    if (error === 'cancel') return
    ElMessage.error('解散群组失败')
    console.error('解散群组失败:', error)
    // 如果失败，重新获取群聊列表
    await roomStore.getGroupRooms()
  }
}

// 退出群组
const quitGroup = async () => {
  if (!selectedGroup.value) return
  
  try {
    await ElMessageBox.confirm(
      '退出群组后，您将不再接收此群的消息，确定要退出吗？',
      '退出群组',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await exitRoomApi(selectedGroup.value.id)
    if (response && response.code === 200) {
      ElMessage.success('已退出群组')
      // 从store中移除该群组
      roomStore.groupRooms = roomStore.groupRooms.filter(g => g.id !== selectedGroup.value.id)
      selectedGroup.value = null
    }
  } catch (error) {
    if (error === 'cancel') return
    ElMessage.error('退出群组失败')
    console.error('退出群组失败:', error)
  }
}

// 处理加入群聊
const handleJoinGroup = async (group) => {
  // 刷新群组列表
  await fetchGroupList()
  // 自动选中新加入的群组
  const joinedGroup = roomStore.groupRooms.find(g => g.id === group.id)
  if (joinedGroup) {
    selectGroup(joinedGroup)
  }
}

onMounted(() => {
  // 如果store中已有群组数据，则不再重新获取
  if (roomStore.groupRooms.length === 0) {
    fetchGroupList()
  }
  
  // 如果有选中的群组，则使用它
  if (selectedGroup.value) {
    fetchGroupList()
  }
})
</script>

<style lang="scss" scoped>
.group {
  .card:hover {
    background-color: var(--card-hover-background-color);
  }
  .card + .card {
    margin-top: 4px;
  }
  ::v-deep(.el-collapse) {
    border: none;
    .el-collapse-item__header {
      height: 30px;
      border: none;
    }
    .el-collapse-item__wrap {
      border: none;
      .el-collapse-item__content {
        line-height: unset;
        padding: 0;
      }
    }
  }
}

.group-panel {
  background-color: var(--card-background-color);
  border-radius: var(--box-border-radius);
  
  .group-panel-info {
    min-width: 100px;
    max-width: 470px;
  }

  .group-info {
    .info-item {
      margin-bottom: 15px;
      
      label {
        font-weight: bold;
        color: var(--font-color);
      }
      
      p {
        margin: 5px 0;
        color: var(--font-secondary-color);
      }
    }
  }
}
</style>
